package queens.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.Resources;

import queens.beans.ClienteBean;
import queens.facades.IClienteFacade;
import queens.forms.BorrarClientesForm;
import queens.util.Constantes;

public class BorrarClientesAction extends QueensAction {
	
	// log de la clase
	@SuppressWarnings("unused")
	private static Log log = LogFactory.getLog(BorrarClientesAction.class);
	
	private IClienteFacade clienteFacade;
	
	private void inicializarFacades(){
		clienteFacade = (IClienteFacade)getBean("clienteFacade");
	}
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		ActionErrors errors                   = (ActionErrors)request.getSession().getAttribute(Globals.ERROR_KEY);
		ActionMessages messages               = new ActionMessages();  
		BorrarClientesForm borrarClientesForm = (BorrarClientesForm)form;
		inicializarFacades();
		
		if("".equals(borrarClientesForm.getAccion())){
			// venimos del action de busqueda
			// cargamos el cliente para mostrarlo
			ClienteBean clienteBean = getClienteFacade().obtenerCliente(borrarClientesForm.getClaveCliente()[0]);
			borrarClientesForm.setClienteBean(clienteBean);
			borrarClientesForm.setAccionSistema(Constantes.ACCION_SISTEMA_BORRAR_CLIENTE);
		}else if(Resources.getMessage(request,"borrar").equals(borrarClientesForm.getAccion())){
			try{
				getClienteFacade().borrarCliente(borrarClientesForm.getClienteBean().getDni());
				messages.add("borrado", new ActionMessage("cliente.borrado.correctamente"));
				// cargamos el cliente para mostrarlo
				ClienteBean clienteBean = getClienteFacade().obtenerCliente(borrarClientesForm.getClienteBean().getDni());
				borrarClientesForm.setClienteBean(clienteBean);
			}catch (Exception e) {
				throw new Exception();
			}
		}else if(Resources.getMessage(request,"salir").equals(borrarClientesForm.getAccion())){
			return mapping.findForward("buscarClientesAction");
		}
		
		saveErrors(request, errors);
		saveMessages(request, messages);
		return mapping.findForward("borrarClientes");
	}
	
	protected IClienteFacade getClienteFacade() {
		return clienteFacade;
	}
}